<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="process-task-container">
          <div class="page-header">
            <h2>工序区管理</h2>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索工序名称或产品型号"
                clearable
                class="search-input"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSearch">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-select v-model="filterStatus" placeholder="状态筛选" clearable @change="handleSearch">
                <el-option label="待生产" value="待生产" />
                <el-option label="生产中" value="生产中" />
                <el-option label="完成" value="完成" />
              </el-select>
            </div>
          </div>

          <!-- 工序区列表 -->
          <el-table :data="processTasks" border style="width: 100%" v-loading="loading">
            <el-table-column prop="taskId" label="工序ID" width="100" />
            <el-table-column prop="processName" label="工序名称" width="200" />
            <el-table-column prop="productModel" label="产品型号" width="200" />
            <el-table-column prop="lineId" label="所属产线" width="120" />
            <el-table-column label="状态" width="150">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createdAt) }}
              </template>
            </el-table-column>
              <el-table-column label="下属设备数量" width="180">
                  <template #default="scope">
                      {{ scope.row.count }}
                  </template>
              </el-table-column>
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status !== '待生产'">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button size="small" type="info" @click="viewEquipment(scope.row)">
                  <el-icon><View /></el-icon> 查看设备
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.status !== '待生产'">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑工序区对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'编辑工序区（将会自动移除设备，请注意重新添加设备）'"
      width="500px"
      destroy-on-close
    >
      <el-form :model="taskForm" :rules="rules" ref="taskFormRef" label-width="100px">
        <el-form-item label="工序名称" prop="processName">
          <el-input v-model="taskForm.processName" placeholder="请输入工序名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看设备对话框 -->
    <el-dialog
      v-model="equipmentDialogVisible"
      title="工序区设备列表"
      width="800px"
    >
      <div v-if="currentTask" class="task-info">
        <h3>{{ currentTask.processName }} - {{ currentTask.productModel }}</h3>
        <p>状态: <el-tag :type="getStatusType(currentTask.status)">{{ currentTask.status }}</el-tag></p>
      </div>

      <el-table :data="equipmentList" border style="width: 100%" v-loading="equipmentLoading">
        <el-table-column prop="equipmentId" label="设备ID" width="80" />
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="type" label="设备类型" width="120" />
        <el-table-column label="设备状态" width="100">
          <template #default="scope">
            <el-tag :type="getEquipmentStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="温度信息" width="200">
          <template #default="scope">
            <div class="temp-info">
              <span>{{ scope.row.currentTemp }}°C / {{ scope.row.tempThreshold }}°C</span>
              <el-progress
                :percentage="getTempPercentage(scope.row.currentTemp, scope.row.tempThreshold)"
                :status="getTempStatus(scope.row.currentTemp, scope.row.tempThreshold)"
                :stroke-width="8"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updatedAt) }}
          </template>
        </el-table-column>
      </el-table>

      <div v-if="equipmentList.length === 0 && !equipmentLoading" class="no-equipment">
        <el-empty description="该工序区暂无设备" />
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要删除工序区 "{{ currentTask?.processName }}" 吗？此操作不可恢复。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getProcessTasks,
    getProcessTaskById,
    getProductionLines,
    updateProcessTasks,
    deleteProcessTaskById, searchProcessTasks
} from '@/api/production'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Plus, Edit, Delete, View, Warning } from '@element-plus/icons-vue'

// 数据定义
const processTasks = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const filterStatus = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const equipmentDialogVisible = ref(false)
const isEdit = ref(false)
const currentTask = ref(null)
const equipmentList = ref([])
const equipmentLoading = ref(false)
const taskmodels = ref([
    "A型LED","B型LED","C型LED","D型LED","E型LED","F型LED"
])
const taskFormRef = ref(null)

// 表单数据
const taskForm = reactive({
  taskId: null,
  processName: '',
  productModel: '',
  lineId: null,
  status: '未开始',
  startTime: null,
  endTime: null
})

// 表单验证规则
const rules = {
  processName: [
    { required: true, message: '请输入工序名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  productModel: [
    { required: true, message: '请输入产品型号', trigger: 'blur' }
  ],
  lineId: [
    { required: true, message: '请选择所属产线', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择工序状态', trigger: 'change' }
  ]
}

// 获取工序区列表
const fetchProcessTasks = async () => {
  loading.value = true
  try {
    const res = await searchProcessTasks({
        name: searchKeyword.value,
        status: filterStatus.value,
      current: currentPage.value,
      size: pageSize.value
    })

    if (res.success) {
      processTasks.value = res.data.records
      total.value = res.data.total
        console.log(res.data)
    } else {
      ElMessage.error(res.message || '获取工序区列表失败')
    }
  } catch (error) {
    ElMessage.error('获取工序区列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchProcessTasks()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProcessTasks()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProcessTasks()
}

// 打开编辑对话框
const handleEdit = (row) => {
  Object.assign(taskForm, {
    taskId: row.taskId,
    processName: row.processName,
    productModel: row.productModel,
    lineId: row.lineId,
    status: row.status,
  })
  dialogVisible.value = true
}

// 查看设备
const viewEquipment = async (row) => {
  currentTask.value = row
  equipmentDialogVisible.value = true
  equipmentLoading.value = true

  try {
    const res = await getProcessTaskById(row.taskId)
    if (res.success) {
      equipmentList.value = res.data.equipmentList || []
    } else {
      ElMessage.error(res.message || '获取设备列表失败')
      equipmentList.value = []
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败')
    equipmentList.value = []
  } finally {
    equipmentLoading.value = false
  }
}

// 打开删除确认对话框
const handleDelete = (row) => {
  currentTask.value = row
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
      const res = await deleteProcessTaskById(currentTask.value.taskId)
      if (res.success){
          ElMessage.success(`工序区 "${currentTask.value.processName}" 已成功删除`)
          deleteDialogVisible.value = false
          await fetchProcessTasks()
      }
      else{
          ElMessage.error(res.message || '删除工序区失败')
      }
  } catch (error) {
    ElMessage.error('删除工序区失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!taskFormRef.value) return

  await taskFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 模拟API调用，实际项目中应替换为真实API
          console.log(taskForm)
          const res = await updateProcessTasks(taskForm)
          console.log(res)
          if (res.success){
              ElMessage.success(`工序区 "${taskForm.processName}" 已成功保存`)
          }
          dialogVisible.value = false
          await fetchProcessTasks()
      } catch (error) {
        ElMessage.error(`工序区编辑失败`)
      }
    }
  })
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '生产中':
      return 'success'
    case '未开始':
      return 'info'
    case '已完成':
      return ''
    default:
      return 'info'
  }
}

// 获取设备状态类型
const getEquipmentStatusType = (status) => {
  switch (status) {
    case '运行':
      return 'success'
    case '维修':
      return 'warning'
    case '停机':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取温度百分比
const getTempPercentage = (current, threshold) => {
  if (!current || !threshold) return 0
  return Math.min(Math.round((current / threshold) * 100), 100)
}

// 获取温度状态
const getTempStatus = (current, threshold) => {
  if (!current || !threshold) return ''
  if (current > threshold * 1.1) return 'exception'
  if (current > threshold) return 'warning'
  return 'success'
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProcessTasks()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.process-task-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.task-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.temp-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.no-equipment {
  padding: 30px 0;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 10px;
}

.warning-icon {
  font-size: 24px;
  color: #F56C6C;
}
</style>
